package com.example.luke.shengdangxiaoattendance;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.luke.shengdangxiaoattendance.Common.CommonActivity;
import com.example.luke.shengdangxiaoattendance.Database.DingHanDB;
import com.example.luke.shengdangxiaoattendance.Dialog.ClassSelectionDialog;
import com.example.luke.shengdangxiaoattendance.Handler.ClassSetupHandler;
import com.example.luke.shengdangxiaoattendance.Model.App;
import com.example.luke.shengdangxiaoattendance.Model.ClassBean;
import com.example.luke.shengdangxiaoattendance.Model.Course;
import com.example.luke.shengdangxiaoattendance.Model.PushBean;
import com.example.luke.shengdangxiaoattendance.Model.Setting;
import com.example.luke.shengdangxiaoattendance.Model.Student;
import com.example.luke.shengdangxiaoattendance.Model.StudentAttendance;
import com.example.luke.shengdangxiaoattendance.Util.ExcelUtils;
import com.example.luke.shengdangxiaoattendance.Util.GlobalFunction;
import com.example.luke.shengdangxiaoattendance.Util.ZYScanner;
import com.example.luke.shengdangxiaoattendance.http.HttpClient;
import com.example.luke.shengdangxiaoattendance.http.HttpResponseHandler;
import com.example.luke.shengdangxiaoattendance.http.NetWorkConstant;
import com.google.gson.Gson;
import com.google.gson.internal.Streams;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.tencent.bugly.crashreport.CrashReport;
import com.wilddog.client.ChildEventListener;
import com.wilddog.client.DataSnapshot;
import com.wilddog.client.SyncError;
import com.wilddog.client.ValueEventListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.IllegalFormatCodePointException;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.Headers;
import okhttp3.Request;

public class MainActivity extends CommonActivity {

    @InjectView(R.id.currentTime)
    TextView currentTime;
    //    @InjectView(R.id.climate)   TextView climate;
//    @InjectView(R.id.temperature)TextView temperature;
//    @InjectView(R.id.airDirection)TextView airDirection;
    @InjectView(R.id.todayDate)
    TextView todayDate;
    @InjectView(R.id.weekDay)
    TextView weekDay;


    @InjectView(R.id.name1)
    TextView name1;
    @InjectView(R.id.time)
    TextView time;
    @InjectView(R.id.name2)
    TextView name2;
    @InjectView(R.id.teacher)
    TextView teacher;

    @InjectView(R.id.className)
    TextView className;


    @InjectView(R.id.totalStudent)
    TextView totStudent;
    @InjectView(R.id.presentStudent)
    TextView preStudent;
    @InjectView(R.id.absentStudent)
    TextView abStudent;

    @InjectView(R.id.container_title_bar)
    LinearLayout containerTit;
    @InjectView(R.id.left_container)
    RelativeLayout leftContainer;

    private int PUSH_MIN_FREQUENCY = 5;//推送频率

    private Course currentCourse;
    int SETTING_CODE = 100;
    int DETAIL_CODE = 101;
    private boolean checkClassCounter = false;
    private int classIndex = 0;
    private ClassSetupHandler classSetupHandler;
    int maxIndex = 0;
    public Date reqDate=new Date();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.center_main_container);
        NetWorkConstant.initNetwork(this);
        Setting.initSetting(this);
        ButterKnife.inject(this);
        initNFCParam();

        classSetupHandler = new ClassSetupHandler(this);
        GlobalFunction.printTextByTag("123213");

        if (Setting.defaultClassName.length() == 0)//先输入课室名称
        {
            gotoActivity(SettingActivity.class, SETTING_CODE);//跳转到设置界面

        } else {

            zyScanner.startRead();//读卡器开始读卡

            name1.setText(Setting.defaultClassName);
            //  reqDataFromHttp();

        }

        initView();//初始化界面


        startCheckClassCounter();//开启后台线程

        initWildDog();//野狗


//        ref.addValueEventListener(new ValueEventListener() {
//            @Override
//            public void onDataChange(DataSnapshot dataSnapshot) {
//                DownloadTask downloadTask=new DownloadTask();
//                downloadTask.execute(1);
//
//
//            }
//
//            @Override
//            public void onCancelled(SyncError syncError) {
//
//            }
//        });


        //  GlobalFunction.printTextByTag("cc");

        checkOfflineModeDownload();

    }



    private void  checkOfflineModeDownload(){

        Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {


                DownloadTask downloadTask=new DownloadTask();
                downloadTask.execute(0);

            }
        },5*60*1000);//5分钟



    }


    public void popUpClassSelection() {

        ArrayList<ClassBean> classBeanArrayList = ExcelUtils.getClassList(this);
        if (classBeanArrayList.size() == 0)
            showDialog();

        else {

            ClassSelectionDialog classSelectionDialog = new ClassSelectionDialog(this);
            classSelectionDialog.setClassBeanArrayList(classBeanArrayList);
            classSelectionDialog.show();
            classSelectionDialog.setClassSelectionListener(new ClassSelectionDialog.ClassSelectionListener() {
                @Override
                public void selectedClass(String className) {

                    name1.setText(className);
                    Setting.saveSetting(MainActivity.this, className);
                    reqDataFromHttp();


                }
            });
        }


    }


    @OnClick(R.id.textCrash)
    void textCrashFunc() {
        CrashReport.testJavaCrash();
    }

    public void showDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // Set the dialog title
        builder.setTitle("请导入教室列表")
                // Specify the list array, the items to be selected by default (null for none),
                // and the listener through which to receive callbacks when items are selected

                // Set the action buttons
                .setPositiveButton("明白", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        popUpClassSelection();
                        // User clicked OK, so save the mSelectedItems results somewhere
                        // or return them to the component that opened the dialog

                    }
                });

        builder.show();

    }


    private String currentCardNo;
    boolean checkTextViewLine = true;


    private void reqDataFromHttp() { //请求数据（从后台获取)

        GlobalFunction.showProgress(this,"请稍后");

        DownloadTask downloadTask=new DownloadTask();
        downloadTask.execute(0);
        downloadTask.reqDate=new Date();


//        DownloadTask downloadTask2=new DownloadTask();
//        downloadTask2.execute(0);
//        downloadTask2.reqDate=GlobalFunction.getNextDay();




    }

    @OnClick(R.id.container_title)
    void containerTitClicked() {

        reqDate=new Date();
        setToEmptyClassState();
        reqDataFromHttp();

    }

    private void setToEmptyClassState() {

        name2.setText("-");
        teacher.setText("-");
        className.setText("-");
        time.setText("-");
        totStudent.setText("-");
        preStudent.setText("-");
        abStudent.setText("-");

    }


    private boolean reloadMark = true;


    private void setUpCourseContent() {

        try {


            currentCourse = Course.getInstance(this).getCurrentCourse();//获取当前课程

            if (currentCourse != null) {
                initCurrentCourseData();


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        reloadStudentCount();//刷新人数

                    }

                });


                Setting.saveRestartMark(this, "1");
                classSetupHandler.setCurrentCourse(currentCourse);


            } else {

                setToEmptyClassState();

            }


        } catch (Exception e) {
            GlobalFunction.printTextByTag(e.getMessage());
        }


    }

    private void initCurrentCourseData() {


        // GlobalFunction.printTextByTag("init course");
        name2.setText(currentCourse.name2);
        time.setText(currentCourse.Time);
        teacher.setText(currentCourse.teacher);


        App.getInstance().currentCourse = currentCourse;


        String[] classSes = (String[]) getClassNameInfo().get("class");
        className.setText(classSes[classIndex]);


        if (name2.getText().length() > 50) {
            String temp = name2.getText().toString().substring(0, name2.length() / 2);
            name2.setText("" + temp + "......");
        }


    }

    private HashMap<String, Object> getClassNameInfo() {

        HashMap<String, Object> classInfo = new HashMap<String, Object>();
        try {


            String sym = ",";
            if (!currentCourse.className.contains(sym))
                sym = ",";

            String[] temp = currentCourse.className.split(sym);
           // GlobalFunction.printTextByTag("class:"+currentCourse.className+":"+classIndex);

            classInfo.put("count", temp.length + "");
            classInfo.put("class", temp);


        } catch (Exception e) {

            e.printStackTrace();
        }


        return classInfo;

    }


    private void exchangeClass() {

        if (currentCourse != null) {

            Integer count = Integer.valueOf(getClassNameInfo().get("count").toString());//分开两个班级

            ++classIndex;

            if (classIndex == count || classIndex>count) {

                classIndex = 0;

            }

            if (classIndex < count) {

                setUpCourseContent();//初始化课程内容


            }


        }

    }

    boolean tempStat = true;

    private void reloadDate() {
        currentTime.setText(GlobalFunction.getTimeWithFomat(new Date(), "HH:mm:ss"));
        todayDate.setText(GlobalFunction.getTimeWithFomat(new Date(), "MM月dd日"));
        weekDay.setText(GlobalFunction.getWeekDay());

    }

    @Override
    public void initView() {
        super.initView();

        PUSH_MIN_FREQUENCY = Setting.getPushFreq(this);




        leftContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                exchangeClass();
                //startReqAttendListForClass();
            }
        });

        reloadDate();


        zyScanner.setZyListener(new ZYScanner.ZYListener() {
            @Override
            public void getCardInfo(Double reduceAmount, Double remain, Double currentBalance) {

            }

            @Override
            public void getMICardNo(String cardNo, String ticketID) {


                try {

                    int temp = Integer.valueOf(cardNo);
                    if (temp == 0) {

                        GlobalFunction.printTextByTag("error");
                        GlobalFunction.ToastAlert(MainActivity.this, "请重新读卡");

                        restartReadCard();

                    } else {

                        gotoDetailCont(cardNo);


                    }


                } catch (Exception e) {

               GlobalFunction.printTextByTag("detailErr:"+e.getMessage());
               e.printStackTrace();

                }


            }

            @Override
            public void showFixPurchaseCost(Double cost) {

            }

            @Override
            public void finishRead() {

                zyScanner.startRead();

            }
        });


        containerTit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               // gotoDetailCont("01704001");
                //CrashReport.testJavaCrash();
                gotoSettingActivity();


            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        GlobalFunction.printTextByTag("3123");


        if (Setting.allowLoop(getApplicationContext()))
            restartApplication();
    }

    private void gotoSettingActivity() {
        zyScanner.stopReadCard();

//     gotoActivity(SettingActivity.class, SETTING_CODE);

       gotoDetailCont("17131001");
  //        CrashReport.testJavaCrash();
    }


    Thread reloadViewThread;


    private void startCheckClassCounter() {


        if (reloadViewThread == null) {


            reloadViewThread = new Thread() {
                @Override
                public void run() {
                    super.run();

                    Timer timer = new Timer();//时间交互
                    timer.schedule(new ReloadView(), 0, 1000);


                    Timer timer2 = new Timer();//课室交换
                    timer2.schedule(new TimerTask() {
                        @Override
                        public void run() {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    exchangeClass();


                                }
                            });


                        }
                    }, 0, 3000);


                }
            };

            reloadViewThread.start();

        }


//        reloadClassThread.stop();


    }

    int viewDetailIndex = 0;


    private void gotoDetailCont(String cardNo) {

        //     GlobalFunction.ToastAlert(this,"读到的卡号:"+cardNo);


        if (currentCardNo == null) {

            currentCardNo = cardNo;

            processCard(cardNo);

        } else {

            if (!currentCardNo.equals(cardNo)) {
                currentCardNo = cardNo;

                processCard(cardNo);

            } else {

                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //Do something here
                        currentCardNo = "";//
                        restartReadCard();
                    }
                }, 1500);
            }
        }


    }


    private void checkClassInfoForStudent(Student respObj) {

        String[] classes = (String[]) getClassNameInfo().get("class");
        int index = 0;
        if (classes != null) {
            for (int i = 0; i < classes.length; i++) {
                String temp = classes[i];
                if (temp.equals(respObj.className)) {
                    index = i;
                    break;
                }
            }
            classIndex = index;
            setUpCourseContent();


        }

    }

    private void processCard(String cardNo) {
        Student respObj = DingHanDB.getInstance(this).getCorrespondingStudent(cardNo);

        if (respObj != null) {
            checkClassInfoForStudent(respObj);

            try {

                if (currentCourse != null) {
                    String startTime = GlobalFunction.convertDate(currentCourse.getStartTime(), "HH:mm:ss");
                    String endTime = GlobalFunction.convertDate(currentCourse.getEndTime(), "HH:mm:ss");

                    //  GlobalFunction.printTextByTag("time："+GlobalFunction.getHourMinDifference(new Date(),currentCourse.getStartTime())+"");


                    if (GlobalFunction.getHourMinDifference(new Date(), currentCourse.getStartTime()) < 45 ||
                            GlobalFunction.isTimeBetweenTwoTime(startTime, endTime))//只能提前一个小时读卡
                    {

                        if (currentCourse.className.contains(respObj.className)) {

                            App.getInstance().selectedStudent = respObj;
//                    MainApp.getInstance().climate=climate.getText().toString();
//                    MainApp.getInstance().airDirection=airDirection.getText().toString();
//                    MainApp.getInstance().temperature=airDirection.getText().toString();
                            App.getInstance().totalStudent = totStudent.getText().toString();
                            App.getInstance().preStudent = preStudent.getText().toString();
                            App.getInstance().currentCourse = currentCourse;

                            zyScanner.stopReadCard();
                            gotoActivity(DetailActivity.class, DETAIL_CODE);


                        } else {


                            restartReadCard();
                            GlobalFunction.ToastAlert(this, "你不属于当前班级学生");
                            GlobalFunction.playMusicFile(MainActivity.this, "absent_fail");
                        }


                    } else {

                        GlobalFunction.ToastAlert(this, "只能在上课前45分钟内刷卡");
                        GlobalFunction.playMusicFile(MainActivity.this, "absent_fail");
                        restartReadCard();


                    }


                } else {

                    GlobalFunction.playMusicFile(MainActivity.this, "absent_fail");
                    GlobalFunction.ToastAlert(MainActivity.this, "请在开始上课期间才开始刷卡");
                    restartReadCard();
                }


            } catch (Exception e) {

                e.printStackTrace();
                restartReadCard();
            }


        } else {
            GlobalFunction.ToastAlert(this, "此卡未登记过");
            GlobalFunction.playMusicFile(MainActivity.this, "absent_fail");
            restartReadCard();
        }


    }


    public void restartReadCard() {

        if (zyScanner != null) {
            zyScanner.stopReadCard();
        }


        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {

                //Do something here
                zyScanner.startRead();
            }
        }, 1000);

    }







    public void reloadStudentCount() {
        String sym = ",";
        if (!className.getText().toString().contains(sym))
            sym = ",";


        String[] classes = (String[]) getClassNameInfo().get("class");
        int temp = 0;


        temp = DingHanDB.getInstance(this).getStudentCountForClass(classes[classIndex]);

//        GlobalFunction.printTextByTag("temp:"+temp);

        int preStudentCount = App.getInstance().getTotalStudentForCurrentClass(classes[classIndex]);

        totStudent.setText("" + temp + "");
        abStudent.setText("" + (temp - preStudentCount) + "");
        preStudent.setText("" + preStudentCount + "");

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == SETTING_CODE) {

            PUSH_MIN_FREQUENCY = Setting.getPushFreq(this);
            name1.setText(Setting.defaultClassName);
            if (resultCode == RESULT_OK) {
                setToEmptyClassState();
                reqDataFromHttp();

            }

        }

        if (requestCode == DETAIL_CODE)
            viewDetailIndex = 0;

        else {

            if (currentCourse != null)
                reloadStudentCount();
        }

        zyScanner.startRead();


    }


    private void pushAttendanceList() {

        classSetupHandler.setPushAttendanceListListener(className.getText().toString(), time.getText().toString(), GlobalFunction.getTimeWithFomat(new Date(), "yyyy-MM-dd"), new ClassSetupHandler.PushAttendanceListListener() {
            @Override
            public void donePush(boolean stat) {
                if (!stat){//如果推送失败，再推

                    pushAttendanceList();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        popUpClassSelection();

    }

    private boolean reqMark = true;
    private boolean pushMark = true;

    class ReloadView extends TimerTask {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    try {

                        if (!Setting.allowUpload(MainActivity.this)) {

                            reqDataFromHttp();

                            reloadDate();

                            Setting.saveDownloadDay(MainActivity.this);

//                            StudentAttendance.clearAttendanceList(MainActivity.this);

                        }


                        if (currentCourse != null) {

                            String startTime = GlobalFunction.convertDate(currentCourse.getStartTime(), "HH:mm:ss");
                            String endTime = GlobalFunction.convertDate(currentCourse.getEndTime(), "HH:mm:ss");
                            long startMinDiff = GlobalFunction.getHourMinDifference(new Date(), currentCourse.getStartTime());


                            if (startMinDiff <= 60 ||
                                    GlobalFunction.isTimeBetweenTwoTime(startTime, endTime))//只能提前一个小时读卡
                            {


                                if (reqMark && GlobalFunction.checkNetWorkStatus(MainActivity.this)) {

                                    reqDate=new Date();
                                    reqDataFromHttp();
                                    reqMark = false;

                                }

                            } else {
                                reqMark = true;

                            }
//                            reqDate=GlobalFunction.getNextDay();
//                            reqDataFromHttp();


                           // GlobalFunction.printTextByTag("stat:"+Course.finishAllClass);
//                            if (Course.finishAllClass){//结束了所有课程
//
//                                GlobalFunction.printTextByTag("cc2132132");
////                                if (reqMark && GlobalFunction.checkNetWorkStatus(MainActivity.this)) {
//
//                                    reqDate=GlobalFunction.getNextDay();
//                                    reqDataFromHttp();
//
//
//
//
//                                Course.finishAllClass=false;
//
//                            }else {}


//
//                                reqMark=true;
//
//                            }







                                if (new Date().after(currentCourse.getEndTime())) {

                                    if (Setting.allowRestart(MainActivity.this)) {

                                        restartApplication();
                                        Setting.saveRestartMark(MainActivity.this, "0");

                                    }
                                }




                        }

                        checkPushAttendanceFrequency();//检查定时推送
                        setUpCourseContent();

                    } catch (Exception e) {

                        e.printStackTrace();
                    }


                    currentTime.setText(GlobalFunction.getTimeWithFomat(new Date(), "HH:mm:ss"));

                }
            });

        }


    }


    private void checkPushAttendanceFrequency(){//检查考勤频率

       String[]time= GlobalFunction.convertDate(new Date(),"HH:mm:ss").split(":");

        Integer totalMin=(Integer.valueOf(time[0])*60)+Integer.valueOf(time[1]);




        if (totalMin%PUSH_MIN_FREQUENCY==0 && Integer.valueOf(time[2])==0 && GlobalFunction.isNetworkAvailable())
             pushAttendanceList();


    }




        private class DownloadTask extends AsyncTask<Integer,Integer,Integer>{

            boolean existData=true;

            public Date reqDate;


            ArrayList<StudentAttendance> attendanceList;

            int currentIndex = 0;

            String[] classes;

            private void reloadAttendanceList() {


                if (currentCourse != null) {

                    attendanceList = new ArrayList<>();
//                    currentIndex = 0;
//
//
//                    classes = (String[]) getClassNameInfo().get("class");
//
//
//                    maxIndex = classes.length;
  //                  startReqAttendListForClass();
                }


            }


            @Override
            protected Integer doInBackground(Integer... params) {
                classSetupHandler.reqDate=reqDate;

                classSetupHandler.setClassListListener(new ClassSetupHandler.ClassListListener() {
                    @Override
                    public void getClassList(boolean noClass) {

                     // GlobalFunction.printTextByTag("ccd:"+noClass);

                        if (noClass) {

                            existData=false;
                            publishProgress();

                        } else {

                            existData=true;
                            reloadAttendanceList();//刷新考勤数据
                        }

                        downloadNextDayClass();



                    }
                });


                return 0;

            }

            private void downloadNextDayClass(){

                classSetupHandler.reqDate=GlobalFunction.getNextDay();

                classSetupHandler.setClassListListener(new ClassSetupHandler.ClassListListener() {
                    @Override
                    public void getClassList(boolean noClass) {

                        // GlobalFunction.printTextByTag("ccd:"+noClass);





                    }
                });
            }


            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);

                if (existData){
                    Setting.saveRestartMark(MainActivity.this, "1");//重启结束课程后的指标。1等于能重启
                    GlobalFunction.ToastAlert(MainActivity.this, "成功获取数据");
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(MainActivity.this, "同步完成");


                }
                else {

                    GlobalFunction.ToastAlert(MainActivity.this, "此课室，今天没有课程");
                    setToEmptyClassState();
                }


            }
        }
}
